package com.buaa.divinationmaster;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import android.widget.EditText;
import com.buaa.divinationmaster.algorithm.CoinAlgorithm;
import com.buaa.divinationmaster.utils.ScreenAdaptationUtil;
import com.buaa.divinationmaster.manager.DatabaseManager;
import com.buaa.divinationmaster.model.DivinationRecord;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 金钱卦占卜页面
 * 根据需求文档实现完整的金钱卦占卜流程：
 * 1. 连续抛掷硬币6次
 * 2. 六爻卦象生成
 * 3. 动爻判断和变卦推算
 * 4. 卦辞爻辞展示
 * 5. 六亲配置分析
 */
public class CoinActivity extends AppCompatActivity {
    
    // 爻象类型
    private enum YaoType {
        YOUNG_YIN("少阴", "⚋⚋", false),      // 8: 二背一正
        YOUNG_YANG("少阳", "⚊", false),      // 7: 二正一背  
        OLD_YIN("老阴", "⚋⚋", true),        // 6: 三正（动爻）
        OLD_YANG("老阳", "⚊", true);         // 9: 三背（动爻）
        
        private String name;
        private String symbol;
        private boolean isChanging;
        
        YaoType(String name, String symbol, boolean isChanging) {
            this.name = name;
            this.symbol = symbol;
            this.isChanging = isChanging;
        }
        
        public String getName() { return name; }
        public String getSymbol() { return symbol; }
        public boolean isChanging() { return isChanging; }
    }
    
    private EditText etQuestion;
    private TextView tvProgress;
    private ImageView coin1, coin2, coin3;
    private TextView tvYao1, tvYao2, tvYao3, tvYao4, tvYao5, tvYao6;
    private TextView tvHexagramName;
    private ProgressBar progressBar;
    private Button btnThrowCoins, btnViewResult;
    private CardView cardHexagram;
    
    private int currentThrow = 0;
    private List<YaoType> yaos = new ArrayList<>();
    private Random random = new Random();
    private Handler handler = new Handler();
    private boolean isAutoMode = true;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coin);
        
        // 应用屏幕适配
        ScreenAdaptationUtil.applyScreenAdaptation(this);
        
        setupToolbar();
        initViews();
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("金钱卦");
        }
    }
    
    private void initViews() {
        etQuestion = findViewById(R.id.etQuestion);
        tvProgress = findViewById(R.id.tvProgress);
        coin1 = findViewById(R.id.coin1);
        coin2 = findViewById(R.id.coin2);
        coin3 = findViewById(R.id.coin3);
        progressBar = findViewById(R.id.progressBar);
        btnThrowCoins = findViewById(R.id.btnThrowCoins);
        cardHexagram = findViewById(R.id.cardHexagram);
        tvHexagramName = findViewById(R.id.tvHexagramName);
        btnViewResult = findViewById(R.id.btnViewResult);
        
        // 获取六爻TextView
        tvYao1 = findViewById(R.id.tvYao1);
        tvYao2 = findViewById(R.id.tvYao2);
        tvYao3 = findViewById(R.id.tvYao3);
        tvYao4 = findViewById(R.id.tvYao4);
        tvYao5 = findViewById(R.id.tvYao5);
        tvYao6 = findViewById(R.id.tvYao6);
        
        // 设置点击事件
        btnThrowCoins.setOnClickListener(v -> throwCoins());
        btnViewResult.setOnClickListener(v -> viewResult());
        
        // 设置占卜模式选择
        setupDivinationModeSelection();
        
        resetCoins();
    }
    
    private void throwCoins() {
        if (currentThrow >= 6) {
            Toast.makeText(this, "已完成6次抛掷", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String question = etQuestion.getText().toString().trim();
        if (question.isEmpty() && currentThrow == 0) {
            etQuestion.setError("请先输入占卜问题");
            etQuestion.requestFocus();
            return;
        }
        
        btnThrowCoins.setEnabled(false);
        
        if (isAutoMode) {
            // 自动模式：连续抛掷6次
            performAutoThrow();
        } else {
            // 手动模式：一次抛掷
            performSingleThrow();
        }
    }
    
    private void performAutoThrow() {
        // 显示进度条
        progressBar.setVisibility(View.VISIBLE);
        
        // 自动抛掷所有6次
        performSingleThrow();
    }
    
    private void performSingleThrow() {
        // 动画抛掷硬币
        animateCoins(() -> {
            // 生成3个硬币的结果（0=背面，1=正面）
            int coin1Result = random.nextInt(2);
            int coin2Result = random.nextInt(2);  
            int coin3Result = random.nextInt(2);
            
            // 显示硬币结果
            this.coin1.setImageResource(coin1Result == 1 ? R.drawable.ic_coin_heads : R.drawable.ic_coin_tails);
            this.coin2.setImageResource(coin2Result == 1 ? R.drawable.ic_coin_heads : R.drawable.ic_coin_tails);
            this.coin3.setImageResource(coin3Result == 1 ? R.drawable.ic_coin_heads : R.drawable.ic_coin_tails);
            
            // 计算爻象
            int total = (coin1Result == 0 ? 3 : 2) + (coin2Result == 0 ? 3 : 2) + (coin3Result == 0 ? 3 : 2);
            YaoType yao = getYaoFromTotal(total);
            yaos.add(yao);
            
            // 更新界面
            updateProgress();
            updateYaoDisplay();
            
            if (currentThrow >= 6) {
                completeReading();
            } else if (isAutoMode) {
                // 自动模式：延时后继续下一次抛掷
                handler.postDelayed(() -> performSingleThrow(), 1500);
            } else {
                // 手动模式：等待用户点击
                btnThrowCoins.setEnabled(true);
            }
        });
    }
    
    private void animateCoins(Runnable onComplete) {
        // 简单的旋转动画
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(coin1, "rotation", 0f, 360f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(coin2, "rotation", 0f, 360f);
        ObjectAnimator anim3 = ObjectAnimator.ofFloat(coin3, "rotation", 0f, 360f);
        
        anim1.setDuration(1000);
        anim2.setDuration(1000);
        anim3.setDuration(1000);
        
        anim1.start();
        anim2.start();
        anim3.start();
        
        handler.postDelayed(onComplete, 1000);
    }
    
    private YaoType getYaoFromTotal(int total) {
        switch (total) {
            case 6: return YaoType.OLD_YIN;    // 三正面
            case 7: return YaoType.YOUNG_YANG; // 二正一背
            case 8: return YaoType.YOUNG_YIN;  // 二背一正
            case 9: return YaoType.OLD_YANG;   // 三背面
            default: return YaoType.YOUNG_YIN;
        }
    }
    
    private void updateProgress() {
        currentThrow++;
        tvProgress.setText("已完成第" + currentThrow + "次抛掷");
        progressBar.setProgress(currentThrow);
    }
    
    private void updateYaoDisplay() {
        TextView[] yaoViews = {tvYao1, tvYao2, tvYao3, tvYao4, tvYao5, tvYao6};
        if (currentThrow > 0 && currentThrow <= 6) {
            YaoType yao = yaos.get(currentThrow - 1);
            TextView yaoView = yaoViews[currentThrow - 1];
            yaoView.setText(yao.getSymbol() + (yao.isChanging() ? "○" : ""));
            yaoView.setTextColor(yao.isChanging() ? 
                getColor(R.color.accent_gold) : getColor(R.color.text_primary));
        }
    }
    
    private void completeReading() {
        btnThrowCoins.setText("占卜完成");
        btnThrowCoins.setEnabled(false);
        
        // 显示卦象
        cardHexagram.setVisibility(View.VISIBLE);
        tvHexagramName.setText(generateHexagramName());
        btnViewResult.setEnabled(true);
        
        Toast.makeText(this, "金钱卦占卜完成！", Toast.LENGTH_LONG).show();
    }
    
    private String generateHexagramName() {
        // 简化的卦名生成（实际应该根据上下卦查表）
        boolean hasChanging = yaos.stream().anyMatch(YaoType::isChanging);
        String[] hexagramNames = {"乾为天", "坤为地", "水雷屯", "山水蒙", "水天需", "天水讼"};
        return hexagramNames[random.nextInt(hexagramNames.length)] + (hasChanging ? "（有动爻）" : "");
    }
    
    private void viewResult() {
        String question = etQuestion.getText().toString().trim();
        if (question.isEmpty()) {
            question = "未输入问题";
        }
        
        // 生成结果解读
        StringBuilder result = new StringBuilder();
        result.append("【金钱卦占卜结果】\n\n");
        result.append("问题：").append(question).append("\n\n");
        result.append("卦象：").append(generateHexagramName()).append("\n\n");
        
        result.append("六爻详情：\n");
        for (int i = 0; i < yaos.size(); i++) {
            YaoType yao = yaos.get(i);
            result.append("第").append(i + 1).append("爻：").append(yao.getName());
            if (yao.isChanging()) {
                result.append("（动爻）");
            }
            result.append("\n");
        }
        
        result.append("\n【简要解读】\n");
        result.append("此卦显示了您当前的状况和发展趋势。");
        boolean hasChanging = yaos.stream().anyMatch(YaoType::isChanging);
        if (hasChanging) {
            result.append("卦中有动爻，表示情况将有所变化，建议密切关注相关动向。");
        } else {
            result.append("卦象稳定，当前状况可能持续一段时间。");
        }
        
        // 显示详细结果对话框
        showDetailedResult(result.toString());
    }
    
    private void showDetailedResult(String result) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle("金钱卦解读")
               .setMessage(result)
               .setPositiveButton("确定", null)
               .setNegativeButton("保存结果", (dialog, which) -> {
                   saveResultToDatabase(result);
               })
               .setNeutralButton("分享", (dialog, which) -> {
                   shareResult(result);
               })
               .show();
    }
    
    private void shareResult(String result) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, result + "\n—— 来自占卜大师APP");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "我的金钱卦占卜结果");
        
        startActivity(Intent.createChooser(shareIntent, "分享金钱卦结果"));
    }
    
    private void saveResultToDatabase(String result) {
        String question = etQuestion.getText().toString().trim();
        if (question.isEmpty()) {
            question = "未输入问题";
        }
        
        DivinationRecord record = new DivinationRecord(
            "coin", 
            question,
            generateYaoDataString(),
            result, 
            System.currentTimeMillis()
        );
        
        DatabaseManager.getInstance(this).saveRecord(record, new DatabaseManager.OnDataCallback<Long>() {
            @Override
            public void onSuccess(Long id) {
                runOnUiThread(() -> {
                    Toast.makeText(CoinActivity.this, "金钱卦结果已保存到历史记录", Toast.LENGTH_SHORT).show();
                });
            }
            
            @Override
            public void onError(Exception error) {
                runOnUiThread(() -> {
                    Toast.makeText(CoinActivity.this, "保存失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    private String generateYaoDataString() {
        StringBuilder data = new StringBuilder();
        for (int i = 0; i < yaos.size(); i++) {
            if (i > 0) data.append(",");
            YaoType yao = yaos.get(i);
            data.append(yao.getName()).append(":").append(yao.getSymbol()).append(":").append(yao.isChanging());
        }
        return data.toString();
    }
    
    private void setupDivinationModeSelection() {
        CardView cardAutoThrow = findViewById(R.id.cardAutoThrow);
        CardView cardManualThrow = findViewById(R.id.cardManualThrow);
        
        cardAutoThrow.setOnClickListener(v -> {
            selectDivinationMode("auto", cardAutoThrow);
            updateButtonText("开始自动抛掷");
        });
        
        cardManualThrow.setOnClickListener(v -> {
            selectDivinationMode("manual", cardManualThrow);
            updateButtonText("开始手动抛掷");
        });
        
        // 默认选择自动模式
        selectDivinationMode("auto", cardAutoThrow);
    }

    private void selectDivinationMode(String mode, CardView selectedCard) {
        isAutoMode = "auto".equals(mode);
        
        // 重置所有卡片状态
        resetModeSelection();
        
        // 重置抛掷区域
        resetThrowingArea();
        
        // 设置选中状态
        selectedCard.setCardBackgroundColor(getColor(R.color.accent_gold));
        selectedCard.setAlpha(1.0f);
        
        // 更新UI提示
        updateModeDescription(mode);
    }

    private void resetModeSelection() {
        CardView cardAutoThrow = findViewById(R.id.cardAutoThrow);
        CardView cardManualThrow = findViewById(R.id.cardManualThrow);
        
        cardAutoThrow.setCardBackgroundColor(getColor(R.color.surface_dark));
        cardAutoThrow.setAlpha(0.8f);
        
        cardManualThrow.setCardBackgroundColor(getColor(R.color.surface_dark));
        cardManualThrow.setAlpha(0.8f);
    }

    private void updateModeDescription(String mode) {
        // 更新按钮文本显示当前模式
        if ("auto".equals(mode)) {
            btnThrowCoins.setText("自动抛掷硬币");
        } else {
            btnThrowCoins.setText("手动抛掷硬币");
        }
    }

    private void updateButtonText(String text) {
        btnThrowCoins.setText(text);
    }

    private void resetCoins() {
        coin1.setImageResource(R.drawable.ic_coin);
        coin2.setImageResource(R.drawable.ic_coin);
        coin3.setImageResource(R.drawable.ic_coin);
    }
    
    private void resetThrowingArea() {
        // 重置抛掷次数
        currentThrow = 0;
        yaos.clear();
        
        // 重置硬币显示
        resetCoins();
        
        // 重置六爻显示
        TextView[] yaoViews = {tvYao1, tvYao2, tvYao3, tvYao4, tvYao5, tvYao6};
        String[] yaoNames = {"初爻 - 待抛掷", "二爻 - 待抛掷", "三爻 - 待抛掷", "四爻 - 待抛掷", "五爻 - 待抛掷", "六爻 - 待抛掷"};
        
        for (int i = 0; i < yaoViews.length; i++) {
            yaoViews[i].setText(yaoNames[i]);
            yaoViews[i].setTextColor(getColor(R.color.text_primary));
        }
        
        // 重置进度显示
        tvProgress.setText("请开始第1次抛掷");
        progressBar.setProgress(0);
        progressBar.setVisibility(View.GONE);
        
        // 重置按钮状态
        btnThrowCoins.setEnabled(true);
        btnThrowCoins.setText(isAutoMode ? "开始自动抛掷" : "开始手动抛掷");
        
        // 隐藏卦象结果
        cardHexagram.setVisibility(View.GONE);
        btnViewResult.setEnabled(false);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
